/**
 * 
 */
package com.ffcs.crmd.tsp.server.job.selecter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;

import com.ffcs.crmd.tsp.server.api.ISelectSendChannel;

import io.netty.channel.Channel;

/**
 * 功能说明:均衡选择发送
 *
 * @author ZHONGFUHUA
 * 
 * @since 2.0.0-SNAPSHOT
 *
 */
public class SelectRebalanceImpl implements ISelectSendChannel<SelectRebalanceParam> {
    
    @Override
    public Channel select(SelectRebalanceParam selectRebalanceParam) {
        Channel destChannel = null;
        List<Channel> ranBeforeChannelList = selectRebalanceParam.getRanBeforeChannelList();
        Map<Channel, Integer> channelsRunningJobNumberMap = selectRebalanceParam.getChannelsRunningJobNumberMap();
        List<Channel> optionChannelList = new ArrayList<Channel>();
        if(MapUtils.isNotEmpty(channelsRunningJobNumberMap)){
            optionChannelList.addAll(channelsRunningJobNumberMap.keySet());
        }
        
        if(CollectionUtils.isNotEmpty(ranBeforeChannelList)){
            optionChannelList.removeAll(ranBeforeChannelList);
        }
        
        if(CollectionUtils.isEmpty(optionChannelList)){
            return destChannel;
        }
        
        destChannel = optionChannelList.get(0);
        int jobDetailMinNum = channelsRunningJobNumberMap.get(destChannel);
        for(Channel channel : optionChannelList){
            int jobDetailNum = channelsRunningJobNumberMap.get(channel);
            if(jobDetailNum < jobDetailMinNum){
                jobDetailMinNum = jobDetailNum;
                destChannel = channel;
            }
        }
        //System.err.println(String.format("Select: channel [%s] number[%s]", destChannel, channelsRunningJobNumberMap.get(destChannel)));
        return destChannel;
    }
    
}
